package datastructure.blockqueue;

public class BlockingQueueTest {
    public static void main(String[] args) throws InterruptedException {
        ArrayBlockingQueue<Integer> queue = new ArrayBlockingQueue<>(2); // 容量为2

        // 生产者线程：不断入队
        Thread producer = new Thread(() -> {
            try {
                int i = 0;
                while (true) {
                    queue.put(i);
                    System.out.println("生产者放入：" + i);
                    i++;
                    Thread.sleep(500); // 放慢生产速度
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        // 消费者线程：不断出队
        Thread consumer = new Thread(() -> {
            try {
                while (true) {
                    int val = queue.take();
                    System.out.println("消费者取出：" + val);
                    Thread.sleep(1000); // 放慢消费速度
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        producer.start();
        consumer.start();
    }
}